/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.table.DefaultTableModel;
import modelo.Tablespace;
import modelo.Usuario;
import modelo.persistencia.BIN;
import modelo.persistencia.XML;

/**
 *
 * @author Andrés
 */
public class VistaConfiguracionesTablespaces extends javax.swing.JFrame {

    /**
     * Creates new form VistaConfiguraciones
     */
    private DefaultTableModel defaultTableModel;
    private Usuario usuarioBD = new Usuario();
    private BIN bin = new BIN();
    private ArrayList<JSpinner> spinners;

    public VistaConfiguracionesTablespaces() {
        initComponents();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setResizable(false);
        inicializarVariables();
    }

    public final void inicializarVariables() {
        usuarioBD = (Usuario) bin.leer();
        this.defaultTableModel = new DefaultTableModel();
        this.spinners = new ArrayList<>();
//        this.defaultTableModel = (DefaultTableModel) tablaCriticos.getModel();
    }

    public void llenarDatos(List<Tablespace> tablespaces) {
        if (defaultTableModel.getRowCount() > 0) {
            for (int i = defaultTableModel.getRowCount() - 1; i > -1; i--) {
                defaultTableModel.removeRow(i);
            }
        }
        this.panelEspacios.removeAll();
        spinners.clear();
        GridLayout experimentLayout = new GridLayout(tablespaces.size(), 2);
        this.panelEspacios.setLayout(experimentLayout);
        for (Tablespace ts : tablespaces) {
            this.defaultTableModel.addRow(new Object[]{ts.getNombre(), String.valueOf(ts.getRango())});
            panelEspacios.add(new JLabel(ts.getNombre()));
            JSpinner spin = new JSpinner();
            spin.setValue(ts.getRango());
            panelEspacios.add(spin);
            spinners.add(spin);
        }
        this.textoCorreo.setText(this.usuarioBD.getEmail());
        this.usuario.setText(this.usuarioBD.getUser());
        this.contrasena.setText(this.usuarioBD.getPassword());
        this.puerto.setText(this.usuarioBD.getPuerto());
        panelEspacios.repaint();
        this.pack();
        this.repaint();

    }

    public void agregarAccionBotonAceptar(ActionListener listener) {
        this.botonAceptar.addActionListener(listener);
    }

    public void agregarListenerGuardar(ActionListener actionListener) {
        this.botonAceptar.addActionListener(actionListener);
    }

    public void guardarCriticos(ArrayList<Tablespace> tablespaces) {
        String ctn = obtenerContrasena();
        if (!usuario.getText().equals("") && !ctn.equals("") && !puerto.getText().equals("")) {
            if (isEmail(textoCorreo.getText())) {
                this.usuarioBD.setEmail(this.textoCorreo.getText());
                this.usuarioBD.setUser(this.usuario.getText());
                this.usuarioBD.setPassword(ctn);
                this.usuarioBD.setPuerto(this.puerto.getText());

                if (bin.escribir(usuarioBD)) {
                    mostrarMensaje("Usuario creado y almacenado correctamente!");
                } else {
                    mostrarMensaje("Usuario no creado! Error");
                }
                setVisible(false);
            } else {
                mostrarMensaje("Formato de Correo Incorrecto!");
            }
        } else {
            mostrarMensaje("Complete todos los campos!");
        }

        int filas = this.defaultTableModel.getRowCount();
        for (int i = 0; i < tablespaces.size(); i++) {
            tablespaces.get(i).setRango((int) spinners.get(i).getValue());
        }

        //JOptionPane.showMessageDialog(null, "Los datos han sido guardados.", "Guardar", WIDTH);
        //this.dispose();
        //return this.ts_criticos;*/
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botonAceptar = new javax.swing.JButton();
        etiquetaCorreo = new javax.swing.JLabel();
        textoCorreo = new javax.swing.JTextField();
        etiquetaContrasena = new javax.swing.JLabel();
        etiquetaUsuario = new javax.swing.JLabel();
        usuario = new javax.swing.JTextField();
        etiquetaPuerto = new javax.swing.JLabel();
        puerto = new javax.swing.JTextField();
        contrasena = new javax.swing.JPasswordField();
        panelTablespaces = new javax.swing.JScrollPane();
        panelEspacios = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Monitor Bases de Datos - Configuraciones");

        botonAceptar.setText("Guardar");
        botonAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botonAceptarMouseClicked(evt);
            }
        });

        etiquetaCorreo.setText("Correo Electronico: ");

        etiquetaContrasena.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        etiquetaContrasena.setText("Contraseña:");

        etiquetaUsuario.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        etiquetaUsuario.setText("Usuario:");

        etiquetaPuerto.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        etiquetaPuerto.setText("Puerto:");

        javax.swing.GroupLayout panelEspaciosLayout = new javax.swing.GroupLayout(panelEspacios);
        panelEspacios.setLayout(panelEspaciosLayout);
        panelEspaciosLayout.setHorizontalGroup(
            panelEspaciosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 292, Short.MAX_VALUE)
        );
        panelEspaciosLayout.setVerticalGroup(
            panelEspaciosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 120, Short.MAX_VALUE)
        );

        panelTablespaces.setViewportView(panelEspacios);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelTablespaces)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(botonAceptar))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(etiquetaCorreo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(etiquetaContrasena, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(etiquetaUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(etiquetaPuerto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textoCorreo)
                            .addComponent(usuario)
                            .addComponent(puerto)
                            .addComponent(contrasena))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etiquetaCorreo)
                    .addComponent(textoCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etiquetaUsuario)
                    .addComponent(usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etiquetaContrasena)
                    .addComponent(contrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(puerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(etiquetaPuerto))
                .addGap(18, 18, 18)
                .addComponent(panelTablespaces)
                .addGap(18, 18, 18)
                .addComponent(botonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    static boolean isEmail(String mail) {
        Pattern p = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(mail);
        return m.matches();
    }

    public void mostrarMensaje(String mensaje) {
        JOptionPane.showMessageDialog(null, mensaje);
    }

    public String obtenerContrasena() {
        char[] pass = this.contrasena.getPassword();
        String contra = "";
        for (int i = 0; i < pass.length; i++) {
            contra += pass[i];
        }
        return contra;
    }

    private void botonAceptarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAceptarMouseClicked
    }//GEN-LAST:event_botonAceptarMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;






                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaConfiguracionesTablespaces.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaConfiguracionesTablespaces.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaConfiguracionesTablespaces.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaConfiguracionesTablespaces.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VistaConfiguracionesTablespaces().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JPasswordField contrasena;
    private javax.swing.JLabel etiquetaContrasena;
    private javax.swing.JLabel etiquetaCorreo;
    private javax.swing.JLabel etiquetaPuerto;
    private javax.swing.JLabel etiquetaUsuario;
    private javax.swing.JPanel panelEspacios;
    private javax.swing.JScrollPane panelTablespaces;
    private javax.swing.JTextField puerto;
    private javax.swing.JTextField textoCorreo;
    private javax.swing.JTextField usuario;
    // End of variables declaration//GEN-END:variables
}
